﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Sinacor.OMM.Translator.Translators.STM
{
    public class BaseTranslator
    {
        private MessageEntity.OriginalMessage _originalMessage;

        public MessageEntity.OriginalMessage OriginalMessage
        {
            get
            {
                return _originalMessage;
            }
            set
            {
                _originalMessage = value;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="_message"></param>
        protected Sinacor.OMM.MessageEntity.BaseMessage TranslateMessageLabel(string label)
        {
            Sinacor.OMM.MessageEntity.STM.BaseMessage baseMessage = new Sinacor.OMM.MessageEntity.STM.BaseMessage();
            char separator = '|';
            string[] ids;

            if (!string.IsNullOrEmpty(OriginalMessage.Label))
            {
                ids = OriginalMessage.Label.Split(separator);
                baseMessage.SequentialID = Convert.ToInt64(ids[0]);
                baseMessage.ID = ids[1];
            }

            return baseMessage;
        }

        /// <summary>
        /// Adjusts the clientId and clientDigit by removing the non numeric characters.
        /// </summary>
        /// <param name="client">The client received from STM.</param>
        /// <param name="clientId">The client ID.</param>
        /// <param name="clientDigit">The digit of the client ID.</param>
        protected void AdjustClient(string client, out int clientId, out byte clientDigit)
        {
            StringBuilder clientNumber = new StringBuilder();
            int number;
            client = client.Substring(0, 10);

            foreach (var item in client)
            {
                if (int.TryParse(item.ToString(), out number))
                    clientNumber.Append(number);
            }

            clientId = Convert.ToInt32(clientNumber.ToString().Substring(0, clientNumber.Length - 1));
            clientDigit = Convert.ToByte(clientNumber[clientNumber.Length - 1].ToString());
        }

        public DateTime GetOperationDate(string messageId)
        {
            string date = messageId.Substring(LayoutCatalog.STM.StmMessage.OperationDate.StartIndex, LayoutCatalog.STM.StmMessage.OperationDate.Length);
            return new DateTime(
                Convert.ToInt32(date.Substring(LayoutCatalog.STM.StmMessage.OperationDate.Year.StartIndex, LayoutCatalog.STM.StmMessage.OperationDate.Year.Length)),
                Convert.ToInt32(date.Substring(LayoutCatalog.STM.StmMessage.OperationDate.Month.StartIndex, LayoutCatalog.STM.StmMessage.OperationDate.Month.Length)),
                Convert.ToInt32(date.Substring(LayoutCatalog.STM.StmMessage.OperationDate.Day.StartIndex, LayoutCatalog.STM.StmMessage.OperationDate.Day.Length))); 
        }
    }
}
